/**
 * 障碍期权组件
 */
import React, { PureComponent } from 'react';
import _ from 'lodash';
import { CloseOutlined, PlusCircleOutlined, PlusCircleTwoTone } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { DatePicker, message } from 'antd';
import { SelectC, InputNumberC, RangeDateC } from '../../../../comps';
import moment from 'moment';
import { connect } from 'dva';
import { config1, dict } from '../config';
import shareOptionStyle from '../shareOptionStyle.less';
@Form.create()
@connect(({ shareOptionManageM, bookM, globalM }) => ({ shareOptionManageM, bookM, globalM }))
export default class BookBarrier extends PureComponent {
  state = {
    Dis1: true, //禁用观察日区间
    observationDateTemp: undefined, // 观察日序列
    observationDate: [],
    Dis2: true, //是否禁用 观察日序列的新增按钮
    Dis3: false, //用判读障碍类型是56还是1234
  };
  componentDidMount() {
    this.props.onRef(this);
    const { bookBarrier } = this.props;
    if (bookBarrier.observationDate) {
      this.setState({
        observationDate: bookBarrier.observationDate.split(','),
      });
    }
    if (bookBarrier.barrierDuration) {
      this.isDurationSelect(bookBarrier.barrierDuration);
    }
    if (bookBarrier.barrierType) {
      this.isDarrierTypeSelect(bookBarrier.barrierType);
    }
  }
  // 获取表单数据
  getSettingInfo = () => {
    const {
      form: { getFieldsValue, validateFieldsAndScroll },
      structure,
    } = this.props;
    let formData = getFieldsValue();
    let result = undefined;
    validateFieldsAndScroll((error, values) => {
      if (error) {
        return false;
      } else {
        // 时间类型的转为字符串
        // formData.bookMain.tradeDate=formData.bookMain.tradeDate?formData.bookMain.tradeDate.format('YYYYMMDD'):''
        let _observationDate = undefined;
        if (this.state.observationDate.length > 0) {
          _observationDate = this.state.observationDate.toString();
        }
        let vo = {
          ...values,
          observationDate: _observationDate,
        };
        vo.observationStart = vo.observationStart ? vo.observationStart.format('YYYYMMDD') : undefined;
        vo.observationEnd = vo.observationEnd ? vo.observationEnd.format('YYYYMMDD') : undefined;
        if (structure === '2') {
          // 1.其他字段必填
          // barrierDuration   观察频率
          // barrierType   障碍类型
          // rebate1    敲出收益率1
          // settleMode 结算方式
          if (!vo.barrierDuration) {
            message.error('观察频率必填');
            return false;
          }
          if (!vo.barrierType) {
            message.error('障碍类型必填');
            return false;
          }

          // 2.当观察频率选择“区间”时 观察日区间 必填。
          if (vo.barrierDuration == '3') {
            if (!(vo.observationStart && vo.observationEnd)) {
              message.error('当观察频率选择“区间”时 观察日区间 必填');
              return false;
            }
          }
          // 3.当观察频率选择“离散”时 观察日序列 必填。
          if (vo.barrierDuration === '4') {
            if (vo.observationDate && vo.observationDate.length > 0) {
            } else {
              message.error('当观察频率选择“离散”时 观察日序列 必填');
              return false;
            }
          }
          // 4.障碍类型为1、2、3、4、5或6时，障碍价格率1和障碍价格1中二选一必填一个。
          if (vo.barrierType) {
            if (!(vo.barrierRate1 || vo.barrier1)) {
              message.error('障碍价格率1和障碍价格1中二选一必填一个');
              return false;
            }
          }
          /**
           * 5.障碍类型为5或6时，障碍价格率2和障碍价格2中二选一必填一个；

            且上面填障碍价格率，下面也得填障碍价格率，

            上面填障碍价格，下面也得填障碍价格；

            障碍价格1要大于障碍价格2，或障碍价格率1要大于障碍价格率2
           */
          if (vo.barrierType === '5' || vo.barrierType === '6') {
            // 障碍价格2必填
            if (!(vo.barrierRate2 || vo.barrier2)) {
              message.error('障碍价格率2和障碍价格2中二选一必填一个');
              return false;
            }
            //选了 障碍价格率1 则障碍价格率2必选
            if (vo.barrierRate1) {
              if (vo.barrierRate2) {
                if (vo.barrierRate1 <= vo.barrierRate2) {
                  message.error('障碍价格率1要大于障碍价格率2');
                  return false;
                }
              } else {
                message.error('填写了障碍价格率1则障碍价格率2必填');
                return false;
              }
            } else {
              // 选了障碍价格1 则障碍价格2必选
              if (vo.barrier2) {
                if (vo.barrier1 <= vo.barrier2) {
                  message.error('障碍价格1要大于障碍价格2');
                  return false;
                }
              } else {
                message.error('填写了障碍价格1则障碍价格2必填');
                return false;
              }
            }
            // 敲出收益率2必填
            if (vo.rebate2 == undefined) {
              message.error('双向敲出、双向敲入的时候，敲出收益率2必填');
              return false;
            }
          }
          //其他情况
          if (vo.rebate1 == undefined) {
            message.error('敲出收益率1必填');
            return false;
          }
          if (!vo.settleMode) {
            message.error('结算方式必填');
            return false;
          }
        }
        result = vo;
      }
    });
    return result;
  };
  // 观察日序列新增
  addTime = () => {
    const { observationDateTemp, observationDate } = this.state;
    let temp = observationDateTemp ? observationDateTemp.format('YYYYMMDD') : undefined;
    let vo = _.cloneDeep(observationDate);
    if (temp) {
      if (!vo.includes(temp)) {
        vo.push(temp);
        this.setState({
          observationDate: vo,
          observationDateTemp: '',
        });
      } else {
        message.error('时间已存在');
      }
    } else {
      message.error('请先选择时间');
    }
  };
  // 观察日序列改变
  observationDateChange = (e) => {
    this.setState({
      observationDateTemp: e,
      Dis2: false,
    });
  };
  // 观察日序列删除
  observationDateDel = (index) => {
    const vo = _.cloneDeep(this.state.observationDate);
    vo.splice(index, 1);
    this.setState({
      observationDate: vo,
    });
  };
  // 对障碍价格和障碍价格率改变
  onChange = (params) => {
    const {
      initialPrice,
      form: { setFieldsValue },
    } = this.props;
    const { key, e } = params;
    if (!initialPrice) {
      message.error('请先填写期初价格');
      this.resetBarrier();
    } else {
      if (key === 'barrier1') {
        // 改变的是障碍价格1
        if (e) {
          setFieldsValue({
            barrierRate1: Math.round((e / initialPrice) * 100 * 100) / 100,
          });
        } else {
          setFieldsValue({
            barrierRate1: undefined,
          });
        }
      }
      if (key === 'barrier2') {
        // 改变的是障碍价格2
        if (e) {
          setFieldsValue({
            barrierRate2: Math.round((e / initialPrice) * 100 * 100) / 100,
          });
        } else {
          setFieldsValue({
            barrierRate2: undefined,
          });
        }
      }
      if (key === 'barrierRate1') {
        // 改变的是障碍价格率1
        if (e) {
          setFieldsValue({
            barrier1: Math.round((e / 100) * initialPrice * 100) / 100,
          });
        } else {
          setFieldsValue({
            barrier1: undefined,
          });
        }
      }
      if (key === 'barrierRate2') {
        // 改变的是障碍价格率2
        if (e) {
          setFieldsValue({
            barrier2: Math.round((e / 100) * initialPrice * 100) / 100,
          });
        } else {
          setFieldsValue({
            barrier2: undefined,
          });
        }
      }
    }
  };
  // 表单重置
  resetForm = () => {
    this.props.form.resetFields();
    this.setState({
      observationDate: [],
      observationDateTemp: undefined,
    });
  };
  // 当baseOption组件里期初价格变化则 ‘障碍价格1，2’，‘障碍价格率1，2’重填
  resetBarrier = () => {
    this.props.form.setFieldsValue({
      barrierRate1: undefined,
      barrier1: undefined,
      barrierRate2: undefined,
      barrier2: undefined,
    });
  };
  // 观察日频率改变
  durationSelect = (e) => {
    this.props.form.setFieldsValue({
      observationStart: undefined,
      observationEnd: undefined,
    });
    this.setState({
      observationDate: [], //清空观察日序列
      observationDateTemp: '',
    });
    if (e) {
      this.isDurationSelect(e);
    }
  };
  isDurationSelect = (e) => {
    // 频率为3 - 区间 ’观察日区间可填
    if (e == '3') {
      this.setState({
        Dis1: false,
      });
    } else {
      this.setState({
        Dis1: true,
      });
    }
    // 频率为4-离散，观察日序列可填
    if (e == '4') {
      this.setState({
        Dis2: false,
      });
    } else {
      this.setState({
        Dis2: true,
      });
    }
  };
  // 障碍类型改变
  // 障碍类型为向上敲入、向下敲入、向上敲出、向下敲出时，障碍价格2、障碍价格率2、敲出收益率2应不可填写；障碍类型为双向敲入、双向敲出的时候，，障碍价格2、障碍价格率2、敲出收益率2应必填
  barrierTypeSelect = (e) => {
    this.props.form.setFieldsValue({
      rebate2: undefined,
      barrierRate2: undefined,
      barrier2: undefined,
    });
    if (e) {
      this.isDarrierTypeSelect(e);
    }
  };
  isDarrierTypeSelect = (e) => {
    if (e == '5' || e == '6') {
      this.setState({
        Dis3: false,
      });
    } else {
      this.setState({
        Dis3: true,
      });
    }
  };
  // 禁选日期设定
  disabledDate = (value) => {
    const { beginDate, endDate } = this.props;
    // 全部禁用传null
    if (beginDate === null && endDate === null) return true;
    let valueF = value.format('YYYYMMDD');
    let disBeginF = beginDate === '' || beginDate === undefined ? '' : beginDate.format('YYYYMMDD') - '01';
    let disEndF = endDate === '' || endDate === undefined ? moment().format('YYYYMMDD') : endDate.format('YYYYMMDD') + '01';
    if (endDate === '' || endDate === undefined) {
      return valueF <= disBeginF;
    } else {
      return valueF <= disBeginF || valueF >= disEndF;
    }
  };
  render() {
    const { Dis1, Dis2, Dis3 } = this.state;
    const {
      bookBarrier,
      structure,
      globalM: { dataDictionary: dictionary },
      bookM: { onlyView },
      beginDate,
      endDate,
    } = this.props;
    const { info } = config1[2]; // 配置文件中 障碍期权的标题配置
    // 整个组件是否可填写
    const disabledImportant = onlyView || (structure == '2' ? false : true);
    // 生成InputNumber
    const generateInputNumber = ({ key, unit, onChange, precision, disabled }) => {
      return (
        <div style={{ width: '100%', height: '39px', marginBottom: info[key].space }}>
          <InputNumberC
            form={this.props.form}
            dataIndex={key}
            title=''
            disabled={disabledImportant || info[key].isGrey || disabled}
            unit={unit}
            precision={precision}
            initialValue={bookBarrier[key]}
            onChange={
              onChange
                ? (e) => {
                    onChange({ key, e });
                  }
                : undefined
            }
            rules={[{ required: info[key].isRequired, message: '此为必填项' }]}
          />
        </div>
      );
    };

    const generateSelect = ({ key, data, isRequired, onChange }) => {
      let dictArr = [];
      if (dict[key] && dictionary[dict[key]]) {
        dictArr = dictionary[dict[key]].map((item) => {
          return { title: item.value, value: item.code };
        });
      }
      let arr = data || dictArr || [];

      return (
        <div style={{ width: '100%', height: '39px', marginBottom: info[key].space }}>
          <SelectC
            dataIndex={key}
            placeholder=''
            form={this.props.form}
            dataSource={arr}
            disabled={disabledImportant || info[key].isGrey}
            onChange={
              onChange
                ? (e) => {
                    onChange(e);
                  }
                : undefined
            }
            initialValue={bookBarrier[key]}
            rules={[{ required: isRequired ? true : info[key].isRequired, message: '此为必填项' }]}
            positionBody={true}
          />
        </div>
      );
    };

    return (
      <div className={shareOptionStyle.bookBarrier}>
        {/* 观察频率 */}
        {generateSelect({ key: 'barrierDuration', onChange: this.durationSelect })}
        {/* 障碍类型 */}
        {generateSelect({ key: 'barrierType', onChange: this.barrierTypeSelect })}
        {/* 观察日区间 */}
        <div className='ant-row' style={{ width: '100%', height: '39px', marginBottom: '10px' }}>
          <RangeDateC
            form={this.props.form} // form对象
            title='' // 显示名称
            dataIndex={['observationStart', 'observationEnd']} // Form识别的下拉选项Item ID
            disabled={disabledImportant || Dis1}
            initialValue={bookBarrier['observationStart'] ? [moment(bookBarrier['observationStart']), moment(bookBarrier['observationEnd'])] : []}
            disableFuture={false}
            hasDataBD={beginDate ? moment(beginDate) : ''}
            hasDataED={endDate ? moment(endDate) : ''}
          />
        </div>
        {/* 观察日序列 */}
        <div className='observationDate'>
          <div className='dateDiv'>
            <div style={{ width: '200px' }}>
              <DatePicker
                disabled={disabledImportant || Dis2}
                style={{ width: '100%' }}
                value={this.state.observationDateTemp}
                onChange={this.observationDateChange}
                format={'YYYY-MM-DD'}
                disabledDate={this.disabledDate}
              />
            </div>
            <div style={{ width: '16px' }}>
              <a onClick={this.addTime}>{Dis2 || disabledImportant ? <PlusCircleOutlined style={{ width: '100%' }} /> : <PlusCircleTwoTone style={{ width: '100%' }} />}</a>
            </div>
          </div>
          <ul className={disabledImportant ? ' listDiv disabled' : 'listDiv'}>
            {this.state.observationDate.map((item, index) => (
              <li key={'observationDate_' + index}>
                <p>{item}</p>
                <a onClick={() => this.observationDateDel(index)}>
                  <CloseOutlined />
                </a>
              </li>
            ))}
          </ul>
        </div>

        {/* 观察价格类型 */}
        {/* {generateSelect({key:'barrierMonitoring'})} */}
        {/* 障碍价格率1 */}
        {generateInputNumber({ key: 'barrierRate1', onChange: this.onChange, precision: 2, unit: '%' })}
        {/* 障碍价格1 */}
        {generateInputNumber({ key: 'barrier1', onChange: this.onChange, precision: 2 })}
        {/* 障碍价格率2 */}
        {generateInputNumber({ key: 'barrierRate2', onChange: this.onChange, precision: 2, disabled: Dis3, unit: '%' })}
        {/* 障碍价格2 */}
        {generateInputNumber({ key: 'barrier2', onChange: this.onChange, precision: 2, disabled: Dis3 })}
        {/* 敲出收益率1 */}
        {generateInputNumber({ key: 'rebate1', precision: 2, unit: '%' })}
        {/* 敲出收益率2 */}
        {generateInputNumber({ key: 'rebate2', disabled: Dis3, precision: 2, unit: '%' })}
        {/* 结算方式 */}
        {generateSelect({ key: 'settleMode' })}
      </div>
    );
  }
}
